package com.sky.Aop;

import com.sky.autoFill.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.JoinPoint;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
public class AutoFillAspect {
    @Pointcut(" execution(* com.sky.mapper.*.*.*(..)) && @annotation(com.sky.autoFill.AutoFill)")
    public void pointcut(){}

    @Before("pointcut()")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //获取签名
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        //获取方法上的自定义注解对象
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        //根据方法的签名获取方法的参数
        Object arg = joinPoint.getArgs()[0];
        if (OperationType.INSERT.equals((autoFill.value()))){
            Method setCreateTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method setUpdateTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setCreateUser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            Method setUpdateUser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            setCreateTime.invoke(arg,LocalDateTime.now());
            setUpdateTime.invoke(arg,LocalDateTime.now());
            setCreateUser.invoke(arg,BaseContext.getCurrentId());
            setUpdateUser.invoke(arg,BaseContext.getCurrentId());
        }else if (OperationType.UPDATE.equals(autoFill.value())){
            Method setUpdateTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setUpdateUser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            setUpdateTime.invoke(arg,LocalDateTime.now());
            setUpdateUser.invoke(arg,BaseContext.getCurrentId());
        }
    }
}
